<template>
  <el-tree ref="treeRef" :data="menuList" show-checkbox node-key="resourceId" :props="defaultProps"
    :default-expanded-keys="resourceIdList" :default-checked-keys="resourceIdList" render-after-expand
    @check="checkChange">
  </el-tree>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { reqAllMenuTreeApi, reqRoleresourceApi } from '@/api/Newuser';
import { useUserStore } from "@/store/modules/user";
const userStore = useUserStore()
const menuList = ref([]);
const defaultProps = {
  children: 'children',
  label: 'resourceName', // 使用resourceName作为显示名称
};
// 原始数据
let rawData = [];
const props = defineProps({
  AddOfUpdata: {
    type: String,
    default: '',
  },
  rolesId: {
    type: String,
    deafult: ''
  }
});
const resourceIdList = ref([] as any)
// 数据预处理函数
const preprocessData = (nodes: any[]) => {
  return nodes.map(node => {
    let processedNode = { ...node, children: [] }; // 初始化children为空数组
    let buttonNodes: any = []; // 用于存储按钮节点

    if (node.children && node.children.length) {
      // 分离按钮节点和普通节点
      node.children.forEach(child => {
        if (child.resourceType === 'button') {
        }
      });

      // 为非按钮节点添加buttonList属性
      if (buttonNodes.length > 0) {
        processedNode.buttonList = buttonNodes.map(button => ({
          ...button,
          selected: false, // 初始化选中状态为false
        }));
      }
    }

    return processedNode;
  });
};
// 获取所有菜单树并预处理数据
const getAllMenuTree = async () => {
  try {
    const res = await reqAllMenuTreeApi({});
    if (res.code === 2000) {
      rawData = res.data;
      menuList.value = rawData as any
    }
  } catch (error) {
    console.error('Failed to fetch menu tree:', error);
  }
};

// 处理复选框选中状态的变化
const checkChange = (data: any, checked: any, indeterminate: boolean) => {
  console.log(checked.checkedKeys)
  userStore.setuserTreelist(checked.checkedKeys)
  // 根据需要处理选中状态的变化
  // 注意：indeterminate状态在树形控件中通常用于表示部分子节点被选中
};

const handleCheckboxChange = (button: any, checked: boolean) => {
  // 处理按钮选中状态的变化
  console.log(button, checked)
  button.selected = checked;
  // 可以在这里添加额外的逻辑，比如发送请求到后端
};

const renderContent = (h, { node, data, store }: any) => {
  return h(
    'span',
    { class: 'custom-tree-node' },
    [
      h('span', null, data.resourceName),
      data.buttonList && data.buttonList.length > 0 ? h(
        'span',
        { class: 'custom-checkbox' },
        data.buttonList.map((button: any) => h(
          ElCheckbox,
          {
            props: { value: button.selected },
            onChange: (checked) => handleCheckboxChange(button, checked)
          }, { default: () => button.resourceName }
        ))
      ) : null,
    ]
  );
};
const getRolesourece = () => {
  reqRoleresourceApi({ roleId: props.rolesId }).then((res: any) => {
    resourceIdList.value = res.data
    userStore.setuserTreelist(resourceIdList.value)
  })
}

onMounted(() => {
  getAllMenuTree();
  if (props.AddOfUpdata == 'updata') {
    setTimeout(() => {
      getRolesourece()
    }, 100);
  } else {
    userStore.setuserTreelist([])
  }
});
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.custom-checkbox {
  white-space: pre-wrap;
}
</style>
